﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI.WebControls;
using mojoPortal.Web;
using Resources;
using ud_SwirlingQuestion.Business;
using mojoPortal.Web.Framework;
using ud_Utilities;
using System.Collections;
using mojoPortal.Business;
using mojoPortal.Web.Editor;

namespace ud_SwirlingQuestion
{
    public partial class SwirlingQuestionPublished : mojoBasePage
    {
        private int pageId = -1;
        private int moduleId = -1;
        private Guid itemGuid = Guid.Empty;
        protected Double timeOffset;
        private TimeZoneInfo timeZone;
        SwirlingQuestionConfiguration config = new SwirlingQuestionConfiguration();
        protected string EditContentImage = WebConfigSettings.EditContentImage;
        protected string DeleteLinkImage = WebConfigSettings.DeleteLinkImage;
        protected string DeleteLinkText = SwirlingQuestionResource.ButtonDelete;
        protected string DeleteLinkImageUrl = string.Empty;
        protected string EditLinkText = SwirlingQuestionResource.ButtonEdit;
        protected string EditLinkImageUrl = string.Empty;
        readonly DBSwirlingQuestion repository = new DBSwirlingQuestion();
        ud_QA item = new ud_QA();

        void Page_Load(object sender, EventArgs e)
        {
            Page.EnableViewState = true;
            SetupScripts();
            if (!UserCanEditModule(moduleId))
            {
                WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
            }
            if (!Page.IsPostBack)
            {
                LoadSettings();
                PopulateLabels();
            }
            PopulateControls();
        }

        private void PopulateControls()
        {
            BindData();
            BindEdit();
        }

        private void BindEdit()
        {
            if (Page.IsPostBack) return;
            if (itemGuid.Equals(Guid.Empty)) return;
            item = repository.GetOne(itemGuid);
            if (item == null)
            {
                dpBeginDate.Text = DateTimeHelper.LocalizeToCalendar(DateTime.UtcNow.AddHours(timeOffset).ToString("g"));
                return;
            }
            txtItemUrl.Text = item.ItemUrl;
            txtCreatedPhone.Text = item.CreatedByPhone;
            txtCreatedName.Text = item.CreatedByName;
            txtCreatedEmail.Text = item.CreatedByEmail;
            ecAnswer.Text = item.Answer;
            txtQuestion.Text = item.Question;
            dpBeginDate.ShowTime = true;
            dpBeginDate.Text = timeZone != null ? item.LastModified.ToLocalTime(timeZone).ToString("g") : DateTimeHelper.LocalizeToCalendar(item.LastModified.AddHours(timeOffset).ToString("g"));
            if (item.IsHot != null) chkIsHot.Checked = item.IsHot.Value;
            txtTitle.Text = item.Title;
            chkIsPublished.Checked = item.IsPublished;
            hdnQuestion.Value = txtTitle.Text;
        }

        private void BindData()
        {
            List<ud_QA> items = repository.GetAllPublished(moduleId);
            gvItems.DataSource = items;
            gvItems.DataBind();
            gvItems.AllowPaging = items.Count > 10;
        }

        private void LoadSettings()
        {
            timeOffset = SiteUtils.GetUserTimeOffset();
            timeZone = SiteUtils.GetUserTimeZone();
            mp1.CssClass += config.CustomCssClass;
        }

        private void PopulateLabels()
        {
            PageTitle = SiteUtils.FormatPageTitle(siteSettings, SwirlingQuestionResource.SwirlingQuestionEditPage);
            lblHeader.Text = SwirlingQuestionResource.SwirlingQuestionEditPage;
            btnBack.Text = SwirlingQuestionResource.ButtonBack;
            btnDelete.Text = SwirlingQuestionResource.ButtonDelete;
            btnSave.Text = SwirlingQuestionResource.ButtonSave;
            gvItems.Columns[0].HeaderText = SwirlingQuestionResource.SwirlingQuestionTitle;
            gvItems.Columns[1].HeaderText = SwirlingQuestionResource.SwirlingQuestionQuestion;
            EditLinkImageUrl = ImageSiteRoot + "/Data/SiteImages/" + EditContentImage;
            DeleteLinkImageUrl = ImageSiteRoot + "/Data/SiteImages/" + DeleteLinkImage;
            if (itemGuid.Equals(Guid.Empty))
            {
                btnDelete.Visible = false;
            }
            Utilities.AddConfirmButton(btnDelete, SwirlingQuestionResource.DeleteConfirmWarning);
            ecAnswer.WebEditor.ToolBar = ToolBar.FullWithTemplates;
            btnUnpublished.Text = SwirlingQuestionResource.UnpublishedQuestion;
            btnUnpublished.PostBackUrl = SiteRoot + "/SwirlingQuestion/Admin/SwirlingQuestionUnpublished.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString();
            btnAll.Text = SwirlingQuestionResource.AllQuestion;
            btnAll.PostBackUrl = SiteRoot + "/SwirlingQuestion/Admin/SwirlingQuestionEdit.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString();
        }

        void btnDelete_Click(object sender, EventArgs e)
        {
            repository.Delete(itemGuid);
            Refresh();
        }

        void btnBack_Click(object sender, EventArgs e)
        {
            WebUtils.SetupRedirect(this, SiteRoot + "/SwirlingQuestion/Admin/SwirlingQuestionEdit.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString());
        }

        private bool ParamsAreValid()
        {
            try
            {
                DateTime.Parse(dpBeginDate.Text);
            }
            catch (FormatException)
            {
                lblError.Text = SwirlingQuestionResource.ParseDateFailureMessage;
                return false;
            }
            catch (ArgumentNullException)
            {
                lblError.Text = SwirlingQuestionResource.ParseDateFailureMessage;
                return false;
            }
            return true;
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            if (!ParamsAreValid()) return;
            string itemURL = string.Empty;
            Guid tempGuid = Guid.Empty;
            item = repository.GetOne(itemGuid);
            if (item != null)
            {
                itemURL = item.ItemUrl;
                tempGuid = item.Guid;
            }
            if (txtItemUrl.Text.Length == 0)
            {
                txtItemUrl.Text = SuggestUrl();
            }
            String friendlyUrlString = SiteUtils.RemoveInvalidUrlChars(txtItemUrl.Text.Replace("~/", String.Empty));
            FriendlyUrl friendlyUrl = new FriendlyUrl(siteSettings.SiteId, friendlyUrlString);

            if (
                ((friendlyUrl.FoundFriendlyUrl) && (friendlyUrl.PageGuid != tempGuid))
                && (itemURL != txtItemUrl.Text)
                )
            {
                lblError.Text = SwirlingQuestionResource.PageUrlInUseBlogErrorMessage;
                return;
            }

            if (!friendlyUrl.FoundFriendlyUrl)
            {
                if (WebPageInfo.IsPhysicalWebPage("~/" + friendlyUrlString))
                {
                    lblError.Text = SwirlingQuestionResource.PageUrlInUseBlogErrorMessage;
                    return;
                }
            }
            string oldUrl = itemURL.Replace("~/", string.Empty);
            string newUrl = SiteUtils.RemoveInvalidUrlChars(txtItemUrl.Text.Replace("~/", string.Empty));
            txtItemUrl.Text = @"~/" + newUrl;
            DateTime localTime = DateTime.Parse(dpBeginDate.Text, CultureInfo.CurrentCulture);
            localTime = timeZone != null ? localTime.ToUtc(timeZone) : localTime.AddHours(-timeOffset);
            if (itemGuid.Equals(Guid.Empty))
            {
                repository.Create(moduleId, txtTitle.Text, txtQuestion.Text, ecAnswer.Text, chkIsPublished.Checked, txtCreatedName.Text, txtCreatedEmail.Text, txtCreatedPhone.Text, SiteUtils.GetCurrentSiteUser().UserId, txtItemUrl.Text, chkIsHot.Checked, out itemGuid, localTime);
            }
            else
            {
                repository.Update(itemGuid, txtTitle.Text, txtQuestion.Text, ecAnswer.Text, chkIsPublished.Checked, txtCreatedName.Text, txtCreatedEmail.Text, txtCreatedPhone.Text, SiteUtils.GetCurrentSiteUser().UserId, txtItemUrl.Text, chkIsHot.Checked, localTime);
            }
            item = repository.GetOne(itemGuid);
            if (!friendlyUrl.FoundFriendlyUrl)
            {
                if ((friendlyUrlString.Length > 0) && (!WebPageInfo.IsPhysicalWebPage("~/" + friendlyUrlString)))
                {
                    FriendlyUrl newFriendlyUrl = new FriendlyUrl
                                                     {
                                                         SiteId = siteSettings.SiteId,
                                                         SiteGuid = siteSettings.SiteGuid,
                                                         PageGuid = item.Guid,
                                                         Url = friendlyUrlString,
                                                         RealUrl = "~/SwirlingQuestion/ViewAnswer.aspx?pageid="
                                                                   + pageId.ToInvariantString()
                                                                   + "&mid=" + moduleId.ToInvariantString()
                                                                   + "&item=" + item.Guid
                                                     };

                    newFriendlyUrl.Save();
                }

                //if post was renamed url will change, if url changes we need to redirect from the old url to the new with 301
                if ((oldUrl.Length > 0) && (newUrl.Length > 0) && (!SiteUtils.UrlsMatch(oldUrl, newUrl)))
                {
                    //worry about the risk of a redirect loop if the page is restored to the old url again
                    // don't create it if a redirect for the new url exists
                    if (
                        (!RedirectInfo.Exists(siteSettings.SiteId, oldUrl))
                        && (!RedirectInfo.Exists(siteSettings.SiteId, newUrl))
                        )
                    {
                        RedirectInfo redirect = new RedirectInfo
                                                    {
                                                        SiteGuid = siteSettings.SiteGuid,
                                                        SiteId = siteSettings.SiteId,
                                                        OldUrl = oldUrl,
                                                        NewUrl = newUrl
                                                    };
                        redirect.Save();
                    }
                    // since we have created a redirect we don't need the old friendly url
                    FriendlyUrl oldFriendlyUrl = new FriendlyUrl(siteSettings.SiteId, oldUrl);
                    if ((oldFriendlyUrl.FoundFriendlyUrl) && (oldFriendlyUrl.PageGuid == item.Guid))
                    {
                        FriendlyUrl.DeleteUrl(oldFriendlyUrl.UrlId);
                    }

                }
            }

            Refresh();
        }
        
        private string SuggestUrl()
        {
            string pageName = txtTitle.Text;
            if (WebConfigSettings.AppendDateToBlogUrls)
            {
                if (timeZone != null)
                {
                    pageName += "-" + DateTime.UtcNow.ToLocalTime(timeZone).ToString("yyyy-MM-dd");
                }
                else
                {
                    pageName += "-" + DateTime.UtcNow.AddHours(timeOffset).ToString("yyyy-MM-dd");
                }

            }
            return SiteUtils.SuggestFriendlyUrl(pageName, siteSettings);
        }

        private void Refresh()
        {
            WebUtils.SetupRedirect(this, SiteRoot + "/SwirlingQuestion/Admin/SwirlingQuestionEdit.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString());
        }

        void gvItems_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("EditItem"))
            {
                itemGuid = new Guid(e.CommandArgument.ToString());
                WebUtils.SetupRedirect(this, SiteRoot + "/SwirlingQuestion/Admin/SwirlingQuestionEdit.aspx?pageid="
                    + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString() + "&item=" + itemGuid);
            }
            else if (e.CommandName.Equals("DeleteItem"))
            {
                itemGuid = new Guid(e.CommandArgument.ToString());
                repository.Delete(itemGuid);
                WebUtils.SetupRedirect(this, SiteRoot + "/SwirlingQuestion/Admin/SwirlingQuestionEdit.aspx?pageid="
                    + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString());
            }
        }

        void gvItems_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvItems.PageIndex = e.NewPageIndex;
            BindData();
        }

        void gvItems_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton ibtnDelete = e.Row.FindControl("ibtnDelete") as ImageButton;
                Utilities.AddConfirmButton(ibtnDelete, SwirlingQuestionResource.DeleteConfirmWarning);
            }
        }


        private void SetupScripts()
        {
            if (!Page.ClientScript.IsClientScriptBlockRegistered("sarissa"))
            {
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "sarissa", "<script src=\""
                    + ResolveUrl("~/ClientScript/sarissa/sarissa.js") + "\" type=\"text/javascript\"></script>");
            }

            if (!Page.ClientScript.IsClientScriptBlockRegistered("sarissa_ieemu_xpath"))
            {
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "sarissa_ieemu_xpath", "<script src=\""
                    + ResolveUrl("~/ClientScript/sarissa/sarissa_ieemu_xpath.js") + "\" type=\"text/javascript\"></script>");
            }

            if (!Page.ClientScript.IsClientScriptBlockRegistered("friendlyurlsuggest"))
            {
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "friendlyurlsuggest", "<script src=\""
                    + ResolveUrl("~/ClientScript/friendlyurlsuggest_v2.js") + "\" type=\"text/javascript\"></script>");
            }

            string focusScript = string.Empty;
            if (itemGuid == Guid.Empty) { focusScript = "document.getElementById('" + txtTitle.ClientID + "').focus();"; }

            string hookupInputScript = "<script type=\"text/javascript\">"
                + "new UrlHelper( "
                + "document.getElementById('" + txtTitle.ClientID + "'),  "
                + "document.getElementById('" + txtItemUrl.ClientID + "'), "
                + "document.getElementById('" + hdnQuestion.ClientID + "'), "
                + "document.getElementById('" + spnUrlWarning.ClientID + "'), "
                + "\"" + SiteRoot + "/Article/BlogUrlSuggestService.ashx" + "\""
                + "); " + focusScript + "</script>";

            if (!Page.ClientScript.IsStartupScriptRegistered(UniqueID + "urlscript"))
            {
                Page.ClientScript.RegisterStartupScript(
                    GetType(),
                    UniqueID + "urlscript", hookupInputScript);
            }
        }

        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
            Load += Page_Load;
            SiteUtils.SetupEditor(ecAnswer);
        }

        protected override void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();
            base.OnInit(e);
            SuppressPageMenu();
            btnSave.Click += btnSave_Click;
            btnBack.Click += btnBack_Click;
            btnDelete.Click += btnDelete_Click;
            gvItems.RowCommand += gvItems_RowCommand;
            gvItems.RowDataBound += gvItems_RowDataBound;
            gvItems.PageIndexChanging += gvItems_PageIndexChanging;
        }

        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", true, moduleId);
            itemGuid = WebUtils.ParseGuidFromQueryString("item", itemGuid);
        }

        private void LoadPanels()
        {
            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            config = new SwirlingQuestionConfiguration(settings);
            bool showLeftColumnAdmin = ConfigHelper.GetBoolProperty("ShowLeftColumnAdmin", false);
            bool showRightColumnAdmin = ConfigHelper.GetBoolProperty("ShowRightColumnAdmin", false);
            bool showTopColumnAdmin = ConfigHelper.GetBoolProperty("ShowTopColumnAdmin", false);
            bool showBottomColumnAdmin = ConfigHelper.GetBoolProperty("ShowBottomColumnAdmin", false);
            int showCenterColumnAdmin = ConfigHelper.GetIntProperty("ShowCenterColumnAdmin", 0);
            LoadSideContent(showLeftColumnAdmin, showRightColumnAdmin, showTopColumnAdmin, showBottomColumnAdmin, showCenterColumnAdmin);
        }

        #endregion
    }
}